package com.forum.message.config;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

/**
 * 数据库初始化器
 * 负责在应用启动时执行SQL脚本创建必要的表结构
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class DatabaseInitializer implements CommandLineRunner {

    private final DataSource dataSource;

    @Override
    public void run(String... args) {
        log.info("初始化数据库结构...");
        try {
            // 加载SQL脚本
            ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
            populator.addScript(new ClassPathResource("db/message-table.sql"));
            
            // 执行SQL脚本
            populator.execute(dataSource);
            log.info("数据库结构初始化成功");
        } catch (Exception e) {
            log.error("数据库结构初始化失败: {}", e.getMessage(), e);
            // 不影响应用启动，可能表已存在
        }
    }
} 